/**
 * 
 */
package com.thon.service.system.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thon.commons.security.utils.Digests;
import com.thon.commons.utils.Encodes;
import com.thon.commons.utils.ImageUrl;
import com.thon.dao.system.UserDao;
import com.thon.entity.system.User;
import com.thon.service.system.UserService;

/**
 * @author THON
 * @mail thon.ju@meet-future.com
 * @date 2012-2-13 下午09:00:06
 * @description
 */
@Service
@Transactional
public class UserServiceImpl implements UserService{
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;
	
	@Autowired
	private UserDao userDao;
	
	@Override
	public void addUser(User user) {
		entryptPassword(user);
		user.setRoles("user");
		user.setRegistDate(new Date());
		user.setLastLoginDate(new Date());
		user.setEnabled(true);
		userDao.save(user);
	}
	
	@Override
	public void updateUser(User user) {
		userDao.update(user);	
	}

	@Override
	public User findUser(String account, Boolean enabled) {
		User user= userDao.findByLoginName(account, enabled);
		return user;
	}

	@Override
	public User getUser(int id) {
		User user= userDao.get(id);
		return user;
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}

	@Override
	public String entryptPassword(String password, String salt) {
		byte[] decodeSalt = Encodes.decodeHex(salt);
		byte[] hashPassword = Digests.sha1(password.getBytes(), decodeSalt, HASH_INTERATIONS);
		return Encodes.encodeHex(hashPassword);
	}

	@Override
	public List<User> listAllUsers() {
		return userDao.listAllUsers();
	}

	@Override
	public void deleteUser(int id) {
		userDao.delete(id);
	}
}
